#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      SunQi
#
# Created:     26/03/2018
# Copyright:   (c) SunQi 2018
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import time,socket,traceback,logging

from PyQt5.QtCore import QThread, pyqtSignal





HOST, PORT = "0.0.0.0", 50005
RECV_BUFFER_SIZE = 4096
SOCKET_TIMEOUT = 6 # 2s
RECV_IMAGE_INTERVAL = 0.1 # dealy 3s  after receive each image

class ReceiverThread(QThread):
    sig_newReceive = pyqtSignal(str)


    def __init__(self, parent=None):
        super(ReceiverThread, self).__init__(parent)

        self.abort = False


    def __del__(self):
        self.abort = True
        self.wait()

    def run(self):
        logging.debug('Thread2 start')

        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.server_socket.bind((HOST, PORT))
        except socket.error as msg:
            logging.error('Bind failed. Error Code : ' + str(msg))
            raise
        self.server_socket.listen(5)

        temp = 1
        time.sleep(5)
        while True:
            if self.abort:
                break
            self.sig_newReceive.emit("send from receiver thread, %s"%temp)
            temp +=1
            time.sleep(30)

        while True:
            if self.abort:
                break

            try:
                client_socket, address = self.server_socket.accept()
                client_socket.settimeout(SOCKET_TIMEOUT)
                data = client_socket.recv(RECV_BUFFER_SIZE)

                client_socket.send('ok'.encode('utf-8'))
                self.sig_newReceive.emit(data.decode('utf-8'))

            except socket.timeout :
                logging.warning( 'receiver Time out in %s second,'%(SOCKET_TIMEOUT))
            except:
                logging.error('receiverThread error %s'% traceback.format_exc())
            finally:
                client_socket.close()
                time.sleep(RECV_IMAGE_INTERVAL)

        logging.info('ReceiverThread Stopped')
        self.server_socket.close()



def main():
    thread_Receiver = ReceiverThread()
    thread_Receiver.start(QThread.NormalPriority)


if __name__ == '__main__':
    main()
